昨天學了權限設定,今天我們試試看設定不同角色去進入不同權限的位置,已模擬多人使用的場景。
啟動 Ubuntu Docker 容器:
docker run -it ubuntu /bin/bash
安裝身分管理的套件:
apt update
apt install -y adduser passwd
# 創建用戶
adduser alice
adduser bob
adduser charlie
# 創建組
groupadd developers
groupadd managers
# 將用戶加入組
usermod -aG developers alice
usermod -aG developers bob
usermod -aG managers charlie
# 創建目錄
mkdir /project
mkdir /project/public
mkdir /project/private
# 創建文件
echo "This is a public file" > /project/public/public_file.txt
echo "This is a private file" > /project/private/private_file.txt
echo "This is a confidential file" > /project/private/confidential_file.txt
# 設置初始權限
chmod 755 /project
chmod 755 /project/public
chmod 700 /project/private
chmod 644 /project/public/public_file.txt
chmod 640 /project/private/private_file.txt
chmod 600 /project/private/confidential_file.txt
# 更改所有權
chown root:developers /project
chown root:developers /project/public
chown root:managers /project/private
chown alice:developers /project/public/public_file.txt
chown bob:developers /project/private/private_file.txt
chown charlie:managers /project/private/confidential_file.txt
使用不同的用戶嘗試訪問文件和目錄:
# 切換到 alice 用戶
su - alice
# 嘗試讀取和修改文件
cat /project/public/public_file.txt
echo "Alice was here" >> /project/public/public_file.txt
cat /project/private/private_file.txt
echo "Alice was here" >> /project/private/private_file.txt
cat /project/private/confidential_file.txt
# 切換到 bob 用戶
su - bob
# 嘗試讀取和修改文件
cat /project/public/public_file.txt
echo "Bob was here" >> /project/public/public_file.txt
cat /project/private/private_file.txt
echo "Bob was here" >> /project/private/private_file.txt
cat /project/private/confidential_file.txt
# 切換到 charlie 用戶
su - charlie
# 嘗試讀取和修改文件
cat /project/public/public_file.txt
echo "Charlie was here" >> /project/public/public_file.txt
cat /project/private/private_file.txt
echo "Charlie was here" >> /project/private/private_file.txt
cat /project/private/confidential_file.txt
echo "Charlie was here" >> /project/private/confidential_file.txt
回到 root 用戶,修改一些權限並再次測試:
# 切換回 root 用戶
exit # 如果你是 charlie,可能需要執行兩次
# 修改權限
chmod 775 /project/private
chmod 664 /project/private/private_file.txt
# 再次使用不同用戶測試訪問
su - alice
cat /project/private/private_file.txt
echo "Alice accessed private file" >> /project/private/private_file.txt
su - bob
cat /project/private/private_file.txt
echo "Bob accessed private file" >> /project/private/private_file.txt
學習到一些基本的Lunix權限管控方式,By User、Group、Other去個別設定r(讀)、w(寫)、x(執行),使用上因為不是GUI方式,有一點抽象,但慢慢熟悉!